export default class {
    status = 'pendding'
    value = undefined
    reason = undefined
    onResolvedCallbacks = []
    onRejectedCallkacks = []
    onCompleteCallbacks = []

    constructor (executor) {
        try {
            executor(this.resolve, this.reject)
        } catch (error) {
            this.reject(error)
        }
    }

    success (onFulfilled) {
        // 获取下this
        let self = this
        if (self.status === 'resolved') {
            onFulfilled(self.value)
        }

        // 如果异步执行则为pending状态
        if (self.status === 'pending') {
            // 保存回调函数
            self.onResolvedCallbacks.push(() => {
                onFulfilled(self.value)
            })
            self.onRejectedCallbacks.push(() => {
                onRejected(self.reason)
            })
        }
        return self
    }

    complete (onCompleted) {
        let self = this
        self.onCompleteCallbacks.push(() => {
            onCompleted(self.value || self.reason)
        })
        return self
    }

    fail (onRejected) {
        let self = this
        if (self.status === 'rejected') {
            onRejected(self.reason)
        }

        // 如果异步执行则为pending状态
        if (self.status === 'pending') {
            // 保存回调函数
            self.onRejectedCallbacks.push(() => {
                onRejected(self.reason)
            })
        }
        return self
    }

    resolve (value) {
        let self = this
        if (self.status === 'pendding') {
            self.value = value
            self.status = 'resolved'
            // 成功之后遍历then中所有的回调函数
            self.onResolvedCallbacks.forEach(fn => fn())
            // 成功之后遍历complete中所有的函数
            self.onCompleteCallbacks.forEach(fn => fn())
        }
    }

    reject (reason) {
        let self = this
        self.reason = reason
        if (self.status === 'pendding') {
            self.reason = reason
            // 失败之后遍历then中所有的回调函数
            self.onRejectedCallkacks.forEach(fn => fn())
            // 失败之后遍历complete中所有的函数
            self.onCompleteCallbacks.forEach(fn => fn())
        }
    }
}